from django.db import transaction
from django.db.models import Sum
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from financial_info.models import PaymentItemModel, PaymentModel


class PaymentItemSerializer(serializers.ModelSerializer):
    """
    付款单中 付款项目 的序列化器
    """
    # 查询当前采购入库单中已经支付金额
    already_payment = serializers.SerializerMethodField(read_only=True, help_text='已经付款的金额')

    class Meta:
        model = PaymentItemModel
        fields = '__all__'

    def get_already_payment(self, obj):
        """
        查询当前采购入库单中已经支付金额
        :param obj: PaymentItemModel
        :return: 0获取其他的数值
        """
        if obj.purchase_storage:
            pay_dict = PaymentItemModel.objects.filter(purchase_storage_id=obj.purchase_storage.id) \
                .exclude(payment__status='0') \
                .aggregate(sum=Sum('this_money'))
            if pay_dict:
                return pay_dict['sum'] if pay_dict['sum'] else 0
            return 0
        return 0


class PaymentSerializer(serializers.ModelSerializer):
    """
    付款单——序列化器
    """
    item_list = PaymentItemSerializer(many=True,required=False)

    class Meta:
        model = PaymentModel
        fields = '__all__'

    def create(self, validated_data):
        if 'item_list' not in validated_data:
            return super(PaymentSerializer, self).create(validated_data)
        item_list = validated_data.pop('item_list')
        with transaction.atomic():
            payment = PaymentModel.objects.create(**validated_data)
            for item in item_list:
                # 插入付款项目
                PaymentItemModel.objects.create(payment=payment, **item)
        return payment

    # 必须重写update
    def update(self, instance, validated_data):
        if instance.status != '0':
            raise ValidationError("付款单已经生效，不能修改!")
        with transaction.atomic():

            if 'item_list' in validated_data:
                item_list = validated_data.pop('item_list')
                old_list = instance.item_list.all()

                if old_list.exists():
                    # 然后把旧数据删除，因为在validated_data拿不到货品库存数据的ID
                    instance.item_list.all().delete()

                for item in item_list:  # 重新插入采购项 数据
                    PaymentItemModel.objects.create(payment=instance, **item)
            result = super(PaymentSerializer, self).update(instance=instance, validated_data=validated_data)
        return result
